package com.skivingcloud.feign.conf;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;

/**
 * 把调用链路中的头也传过去（session等）
 * @author hushouquan
 */
@Configuration
@Component
@EnableFeignClients(basePackages = "com.**.feignclient")
public class  FeignClientsConfigurationCustom implements RequestInterceptor{
    @Resource
    private CommonFeignPropertiesConfig commonFeignPropertiesConfig;
    @Override
    public void apply(RequestTemplate requestTemplate){
        //服务间认证用的token
        requestTemplate.header("feignAccessToken", commonFeignPropertiesConfig.getFeignAccessToken());
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return;
        }
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                if("content-length".equalsIgnoreCase(name)){
                    continue;
                }
                requestTemplate.header(name, values);
            }
        }
    }
}
